﻿using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using System.Diagnostics;
using YamrSyncDemo.DBSync;
using YamrSyncDemo.YammerData;
using YamrSyncLib.DBSync;

namespace YamrSyncLib.DBDataEnrichment
{
    /// <summary>
    /// Perform data operations on saved message data.
    /// </summary>
    public class MessageEnrichment
    {
        YammerDB yammerDB;
        public MessageEnrichment(YammerDB yammerDB)
        {
            this.yammerDB = yammerDB;
        }

        /// <summary>
        /// Count the replies per message and add the count to the respective message. If there is already a count it will be upated. 
        /// Messages with no replies won't get the field.
        /// 
        /// Field name: reply_count
        /// </summary>
        public void AddOrUpdateReplyCount()
        {
            var messages = yammerDB.MongoDatabase.GetCollection<YammerMessage>(CollectionNames.Messages);
            // get messages that have been replied to
            var map = @"
                function() {
                    var msg = this;
                    emit(msg.RepliedToID, 1 );
                }";
            // count replies
            var reduce = @"        
                function(key, values) {
                    var result = 0;

                    values.forEach(function(value){               
                        result += value;
                    });

                    return result;
                }";
            // map reduce operation
            var options = new MapReduceOptionsBuilder();
            options.SetOutput(MapReduceOutput.Inline);
            var results = messages.MapReduce(map, reduce, options);
            foreach (var result in results.GetResults())
            {
                Debug.WriteLine(result.ToJson());
                // e.g.: { "_id" : NumberLong(328047604), "value" : 2.0 }
                if (result["_id"].IsInt64)
                {
                    var count = result["value"].ToInt64();
                    messages.Update(Query<YammerMessage>.EQ(e => e.ID, result["_id"].ToInt64()), Update.Set("reply_count", count), UpdateFlags.Upsert);
                }
            }
        }
    }
}
